<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--用户数据-->
            <el-col :span="24" :xs="24">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" >
                    <el-form-item label="文章名称" prop="articleTitle">
                        <el-input v-model="queryParams.articleTitle" placeholder="请输入文章名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="文章类型" prop="articleType">
                        <el-select  v-model="queryParams.articleType" placeholder="请选择文章类型" @keyup.enter.native="handleQuery" clearable>
                            <el-option label="视频" :value="0"></el-option>
                            <el-option label="文档" :value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="文章状态" prop="articleStatus">
                        <el-select  v-model="queryParams.articleStatus" placeholder="请选择文章状态" @keyup.enter.native="handleQuery" clearable>
                            <el-option label="启用" :value="0"></el-option>
                            <el-option label="禁用" :value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" >搜索</el-button >
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
                    </el-form-item>
                </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" >新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column :label=columns[0].label align="center" key="id" prop="id" v-if="columns[0].visible" />
          <el-table-column :label=columns[1].label align="center" key="articleTitle" prop="articleTitle" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column :label=columns[2].label align="center" key="articleType" prop="articleType" v-if="columns[2].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{scope.row.articleType=='0'?"视频":scope.row.articleType=='1'?"文章":"错误信息"}}</span>
            </template>
          </el-table-column>
          <el-table-column :label=columns[3].label align="center" key="articleStatus" prop="articleStatus" v-if="columns[3].visible" >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.articleStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="0"
                inactive-value="1" @change="upSwitch(scope.row)">
            </el-switch>
            </template>
          </el-table-column>
          <el-table-column :label=columns[4].label align="center" key="userName" prop="userName" v-if="columns[4].visible" />
          <el-table-column :label=columns[5].label align="center" key="createTime" prop="createTime" v-if="columns[5].visible" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-document-copy" @click="openInfo(scope.row)">详细</el-button>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <!-- 添加文章对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :before-close="dialogClose">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-form-item label="文章标题" prop="articleTitle">
                        <el-input v-model="form.articleTitle" placeholder="请输入文章标题" maxlength="30"  show-word-limit clearable></el-input>
                    </el-form-item>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="文章类型" prop="articleType">
                            <el-radio-group v-model="form.articleType">
                                <el-radio :label="0">视频</el-radio>
                                <el-radio :label="1">文档</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="form.articleType=='0'">
                        <el-form-item label="文章视频" label-width="80px">
                            <el-upload class="upload-demo" :before-upload="beforeVideoUpload" action="">
                                <el-button size="mini" type="primary">上传视频</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="form.articleType=='1'">
                        <el-form-item label="文章图片" label-width="80px">
                            <el-upload class="upload-demo" :before-upload="beforeAvatarUpload" action="">
                                <el-button size="mini" type="primary">上传图片</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <div style="margin:0 auto;  margin-bottom: 22px;">
                        <el-image style="width: 52%;margin-left:80px" v-if="filePath&&form.articleType=='1'" :src="filePath" class="avatar" ></el-image>
                        <video width="100%" autoplay controls loop :src="videoPath" v-if="videoPath&&form.articleType=='0'"></video>
                    </div>
                </el-row> 
                <el-row>
                    <el-col :span="24" v-if="form.articleType=='1'">
                        <el-form-item label="文档内容" prop="content">
                            <textarea v-model="form.content" class="fixed-textarea"></textarea>
                        </el-form-item>
                    </el-col>
                </el-row>               
                
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm('form')">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 修改文章对话框 -->
        <el-dialog :title="title" :visible.sync="upopen" width="800px" append-to-body :before-close="upDialogClose">
            <el-form ref="form" :model="form" :rules="form" label-width="80px">
                <el-row>
                    <el-form-item label="文章标题" prop="articleTitle">
                        <el-input v-model="form.articleTitle" placeholder="请输入文章标题" maxlength="30"  show-word-limit clearable></el-input>
                    </el-form-item>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="文章类型" prop="articleType">
                            <el-radio-group v-model="form.articleType" disabled >
                                <el-radio label="0">视频</el-radio>
                                <el-radio label="1">文档</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="form.articleType=='0'">
                        <el-form-item label="文章视频" label-width="80px">
                            <el-upload class="upload-demo" :before-upload="beforeVideoUpload" action="">
                                <el-button size="mini" type="primary">上传视频</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="form.articleType=='1'">
                        <el-form-item label="文章图片" label-width="80px">
                            <el-upload class="upload-demo" :before-upload="beforeAvatarUpload" action="">
                                <el-button size="mini" type="primary">上传图片</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <div style="margin:0 auto;  margin-bottom: 22px;">
                        <el-image style="width: 52%;margin-left:80px" v-if="filePath&&form.articleType=='1'" :src="filePath" class="avatar" ></el-image>
                        <video width="100%" autoplay controls loop :src="videoPath" v-if="videoPath&&form.articleType=='0'"></video>
                    </div>
                </el-row> 
                <el-row>
                    <el-col :span="24" v-if="form.articleType=='1'">
                        <el-form-item label="文档内容" prop="content">
                            <textarea v-model="form.content" class="fixed-textarea"></textarea>
                        </el-form-item>
                    </el-col>
                </el-row>               
                
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm('form')">确 定</el-button>
                <el-button @click="upcancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 文章详细 -->
        <el-dialog :title="title" :visible.sync="infoButton" width="800px" append-to-body :before-close="infoDialogClose">
            <el-form ref="infoform" :model="infoform" label-width="80px">
                <el-row>
                    <el-form-item label="文章标题" prop="articleTitle" >
                        <el-input v-model="infoform.articleTitle" placeholder="请输入文章标题" maxlength="30" disabled></el-input>
                    </el-form-item>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="文章类型" prop="articleType">
                            <el-radio-group v-model="infoform.articleType" disabled>
                                <el-radio label="0">视频</el-radio>
                                <el-radio label="1">文档</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="文章状态" prop="articleType">
                            <el-radio-group v-model="infoform.articleStatus" disabled>
                                <el-radio label="0">启用</el-radio>
                                <el-radio label="1">禁用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col>
                    </el-col>
                </el-row>
                <el-row>
                    <div style="margin:0 auto;  margin-bottom: 22px;">
                    <el-form-item label="文章封面" prop="articleType" v-if="filePath&&infoform.articleType=='1'">
                            <el-image style="height: 200px;margin-left:80px" :src="filePath" class="avatar" ></el-image>
                        </el-form-item>
                        <el-form-item label="文章视频" prop="articleType"  v-if="videoPath&&infoform.articleType=='0'">
                            <video width="100%" autoplay controls loop :src="videoPath"></video>
                        </el-form-item>
                        
                        
                    </div>
                </el-row> 
                <el-row>
                    <el-col :span="24" v-if="infoform.articleType=='1'" >
                        <el-form-item label="文档内容" prop="content">
                            <textarea v-model="infoform.content" class="fixed-textarea" disabled></textarea>
                        </el-form-item>
                    </el-col>
                </el-row>               
                
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="closeInfo">确 定</el-button>
            </div>
        </el-dialog>
      </el-col>
    </el-row>
    </div>  
</template>

<script>
    import { getUserProfile } from "@/api/system/user";
    import { addArticle,listArticle,listArticleById,deleteArticle,updateArticle,changeArticleStatus } from "@/api/article/index";
    import { getToken } from "@/utils/auth";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    let pcas = require("@/pcas/pcas-code.json")
export default {
    name: "User",
    dicts: ["sys_normal_disable", "sys_user_sex"],
    components: { Treeselect },
    watch: {
    documentContent(newContent) {
      this.paragraphs = newContent.split("\n");
    }
  },
    data(){
        return{
            documentContent: "",
      paragraphs: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                articleTitle: undefined,
                articleType: undefined,
                articleStatus: undefined
            },
            // 弹窗标题
            title: '',
            // 总条数
            total: 0,
            // 图片路径
            filePath: '',
            // 视频路径
            videoPath: '',
            // 文件
            file1: '',
            // 文件
            file2: '',
            // 显示搜索条件
            showSearch: true,
            // 列信息
            columns: [
                { key: 0, label: `文章编号`, visible: true },
                { key: 1, label: `文章标题`, visible: true },
                { key: 2, label: `文章类型`, visible: true },
                { key: 3, label: `文章状态`, visible: true },
                { key: 4, label: `作者`, visible: true },
                { key: 5, label: `创建时间`, visible: true },
            ],
            // 修改表单
            updateform:{},
            // 修改弹窗开关
            upopen:false,
            // 详细信息表单
            infoform:{},
            // 详细信息弹窗开关
            infoButton:false,
            // 添加表单
            form:{},
            // 添加弹窗开关
            open: false,
            // 遮罩层
            loading: true,
            // 数据表格 
            userList:[],
            // id数组
            ids:[],
            // 表单校验
            rules: {
                articleTitle: [
                    { required: true, message: "文章标题不能为空", trigger: "blur" }
                ],
                articleType: [
                    { required: true, message: "文章类型不能为空", trigger: "blur" }
                ],
                content: [
                    { required: true, message: "文章类型不能为空", trigger: "blur" }
                ]
            },
            // 用户表单
            user:{}
        }
    },
    computed: {
        transformOptions() {
        return this.options.map(province => ({
            value: province.name,
            label: province.name,
            children: province.children.map(city => ({
            value: city.name,
            label: city.name,
            children: city.children.map(county => ({
                value: county.name,
                label: county.name,
                children: county.children.map(town => ({
                value: town.name,
                label: town.name
                }))
            }))
            }))
        }));
        }
    },
    mounted(){
        this.getList()
        this.getUser()
    },
    methods:{
        /** 打开详细信息弹窗 */
        openInfo(row){
            this.infoform=row
            if(row.articleType=='0'){
                // this.videoPath = process.env.VUE_APP_VIDEO_BASE_URL + row.filePath;
                this.videoPath = 'http://101.43.223.224:8765/image/playVideoById?id='+ row.filePath
            }
            if(row.articleType=='1'){
                this.filePath = process.env.VUE_APP_IMG_BASE_URL + row.filePath;
                
            }
            this.title='文章详细'
            this.infoButton=true
            
        },
        /** 关闭详细信息弹窗 */
        closeInfo(){
            this.infoButton=false
            this.reset();
            this.videoPath=''
            this.filePath=''
        },
        /** 更改类型时触发操作 */
        changeRadio() {
            this.videoPath=''
            this.filePath=''
            this.file2=''
            this.file=''
            this.file1=''
        },
        /** 搜索按钮操作 */
        getUser() {
            getUserProfile().then(response => {
                this.user = response.data.profile;
                console.log(this.user)
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery(queryForm) {
            this.resetForm("queryForm");
            // this.$refs.tree.setCurrentKey(null);
            this.$refs[queryForm].resetFields();
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            // 重置表单
            this.reset();
            this.open = true;
            this.title = "添加文章信息";
        },
        /** 修改弹窗关闭执行前操作 */
        upDialogClose() {
            // 重置表单
            this.reset();
            this.file1=''
            this.file2=''
            this.videoPath=''
            this.filePath=''
            this.upopen = false;
        },
        /** 详细信息弹窗关闭执行前操作 */
        infoDialogClose(){
            // 重置表单
            this.reset();
            this.file1=''
            this.file2=''
            this.videoPath=''
            this.filePath=''
            this.infoButton = false;
        },
        /** 添加弹窗关闭执行前操作 */
        dialogClose() {
            // 重置表单
            this.reset();
            this.file1=''
            this.file2=''
            this.videoPath=''
            this.filePath=''
            this.open = false;
        },
        // 表单重置
        reset() {
            this.form = {
                articleType:0
            };
            this.filePath = '';
            this.resetForm("form");
        },
         // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
         // 修改取消按钮
        upcancel() {
            this.upopen = false;
            this.reset();
        },
        // 修改按钮
        handleUpdate(row) {
            if(row.articleType=='0'){
                // this.videoPath = process.env.VUE_APP_VIDEO_BASE_URL + row.filePath;
                this.videoPath = 'http://101.43.223.224:8765/image/playVideoById?id='+ row.filePath
            }
            if(row.articleType=='1'){
                this.filePath = process.env.VUE_APP_IMG_BASE_URL + row.filePath;
                
            }
            this.form = JSON.parse(JSON.stringify(row))
            this.upopen = true;
            this.title = "修改文章信息";
        },
        /** 查询用户列表 */
        getList() {
            this.loading = true;
            listArticle(this.queryParams).then(
                (res) => {
                this.userList = res.data.content;
                this.total = res.data.totalSize;
                this.loading = false;
                }
            );
        },
        /** 删除按钮操作 */
        handleDelete(row) {
        const articleIds = row.id || this.ids;
        this.$modal.confirm('是否确认删除文章编号为"' + articleIds + '"的数据项？').then(function() {
            return deleteArticle(articleIds);
        }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
        },
        /** 修改状态按钮操作 */
        upSwitch(row){
            let text = row.articleStatus === "0" ? "启用" : "停用";
            this.$modal.confirm('确认要' + text + '标题为"' + row.articleTitle + '"的文章吗？').then(function() {
             return changeArticleStatus(row.id,row.articleStatus)
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
                
            }).catch(function() {
            row.articleStatus = row.articleStatus === "0" ? "1" : "0";
            });
        },
        /** 提交按钮 */
        submitForm: function() {
            const formData = new FormData();
                    if(this.form.articleType=='0'){
                        if(this.videoPath == ''||this.videoPath == undefined){
                            return this.$message.warning("请上传视频");
                        } else{
                            this.form.content ='视频文件';
                            if(this.file2!=null&&this.file2!=''){
                                formData.set("file", this.file2, this.file2.name);
                            }
                        }
                    }else if(this.form.articleType=='1'){
                        if(this.filePath == ''||this.filePath == undefined){
                        return this.$message.warning("请上传图片");
                        } else{
                            if(this.file1!=null&&this.file1!=''){
                                formData.set("file", this.file1, this.file1.name);
                            }
                        }
                    } else{
                        return this.$message.error("参数校验失败!!!")
                    }
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.form.author=this.user.id
                    for (const key in this.form) {
                        formData.set(key, this.form[key])
                    }
                    console.log(formData)
                if (this.form.id != undefined) {
                    updateArticle(formData).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.upopen=false
                    this.getList();
                    });
                } else {
                    addArticle(formData).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                    });
                }
                }
            });
        },
        // 图片上传校验
        beforeAvatarUpload(file) {
            //上传图片格式
            const isJPG = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG && !isPNG) {
                this.$message.error("上传图片只能是JPG/PNG格式!");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过2MB!");
                return false;
            }
            this.file1 = file;
            this.filePath = URL.createObjectURL(file);
            return false;
        },
        // 图片上传校验
        beforeVideoUpload(file) {
            //上传图片格式
            const isJPG = file.type === "video/mp4";
            if (!isJPG) {
                this.$message.error("上传视频只能是MP4格式!");
                return false;
            }
            this.file2 = file;
            this.videoPath = URL.createObjectURL(file);
            return false;
        },
    }

}
</script>

<style>
    .fixed-textarea {
  width: 100%; /* 设置文本域的宽度 */
  resize: none; /* 禁止文本域调整大小 */
  border: 0px solid black;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  height: 500px;
}
</style>